package com.itheima.reggie.controller;


import com.itheima.reggie.common.ResultInfo;
import com.itheima.reggie.domain.Address;
import com.itheima.reggie.service.AddressService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Map;

@RestController
public class AddressController {

    @Autowired
    private AddressService addressService;

    /*地址列表查询*/
    @GetMapping("/address/list")
    public ResultInfo addressList() {
        List<Address> addressList = addressService.findList();
        return ResultInfo.success(addressList);
    }


    /*添加地址*/
    @PostMapping("/address")
    public ResultInfo add(@RequestBody Address address) {
        addressService.add(address);
        return ResultInfo.success(null);
    }

    /*地址查询*/
    @GetMapping("/address/{id}")
    public ResultInfo findById(@PathVariable("id") Long id) {
        Address address = addressService.findById(id);
        return ResultInfo.success(address);
    }

    /*修改地址*/
    @PutMapping("/address")
    public ResultInfo update(@RequestBody Address address) {
        Address address1 = addressService.update(address);
        return ResultInfo.success(address1);
    }

    /*设置默认地址*/
    @PutMapping("/address/default")
    public ResultInfo setDefault(@RequestBody /*Address address*/ Map<String ,Long> map) {
//        Address address1 = addressService.setDefault(address);
        Long id = map.get("id");
        addressService.setDefault(id);
        return ResultInfo.success(null);
    }

    /*获取默认地址*/
    @GetMapping("/address/default")
    public ResultInfo getDefault() {
        Address address = addressService.getDefault();
        if (address == null) {
            return ResultInfo.error("没有默认地址");
        } else {
            return ResultInfo.success(address);
        }
    }


    /*删除地址*/
    @DeleteMapping("/address")
    public ResultInfo delete(@RequestParam("ids") Long id) {
        addressService.deleteById(id);
        return ResultInfo.success(null);
    }

}
